  <template>
  <div>
    <div>
      <BasicTable @register="registerTable" @row-click="handleTestDataChildRowClick" @selection-change="handleSelectionChange">
        <!-- 表格标题 -->
        <template #tableTitle>
          <Icon :icon="getTitle.icon" class="m-1 pr-1" />
          <span> {{ getTitle.value }} </span> 
          <span style="margin-left: 10px">
            <Icon icon="i-ant-design:check-outlined" color="default" /> <span style="color:blue">{{ t('本次到货总重量 : ') }} </span><span style="color:red"> {{ totalWeight ? totalWeight : '0.0000' }} </span>
          </span>
        </template>
        <!-- 表格右上角自定义按钮（新增...） -->
        <template #toolbar>
          <div>
            <Popconfirm :title="t('确认推送吗?')" @confirm="btnSdPush()">
              <a-button
                ghost
                type="warning"
                v-auth="'mf:dh:mfCarplanDhH:edit'"
                class="ml-2 mr-2"
              >
                <Icon icon="i-ant-design:arrow-right-outlined" /> {{ t('批量推送') }}({{ selectedRowKeysRef.length }})
              </a-button>
          </Popconfirm>
          </div>
        </template>
      </BasicTable>
      <InputForm @register="registerDrawer" @success="handleSuccess" />
    </div>
    <!-- 子表 -->
    <BasicModal
      v-bind="$attrs"
      :showFooter="true"
      :okAuth="'mf:dh:mfCarplanDhH:edit'"
      @register="registerModal"
      @ok="handleOverSubmit"
    >
      <template #title>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> 修改原因：  </span> {{ overData.djNo }}
      </template>
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script lang="ts">
  export default defineComponent({
    name: 'ViewsWmsWeighbridgeDhPushErpListDz',
  });
</script>
<script lang="ts" setup>
  import { Popconfirm } from 'ant-design-vue';
  import { defineComponent, watch, ref, onMounted, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    mfCarplanDhHListData, mfCarplanDhCListData, mfCarplanDhHinvalid,
    updatePushStatusByHand, mfCarplanDhHDelete,  mfCarplanDhHupdateCstatus,
    mfCarplanDhCDelete, updateCzStatusByHand, mfCarplanDhCsaveChild, mfCarplanDhHformEdit ,listPushData,pushdata,CarplanDhDelete
  } from '/@/api/wms/weighbridge/dh';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps,BasicForm, FormSchema, useForm } from '/@/components/Form';
  import InputForm from './../form2.vue';
  import { useModal } from '/@/components/Modal';
 

  const emit = defineEmits(['success']);

  const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('入库装车推送-单装'),
  };
  const props = defineProps({
    data: { type: Object, default: {} },
  });
  watch(
    () => props.data,
    () => { },
    { immediate: true },
  );
  let zbData = ref < string > ('');
  let djNo = ref < string > ('');
  let hid = ref < string > ('');
  let overData = ref < any > ({});
  let queryParams = ref< any >({});
  //定义totalWeight 初始值为0.0000
  const totalWeight = ref < number > (0.0000);




  const [registerModal, { openModal, closeModal,setModalProps }] = useModal();


  //配置表单内容
  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 120,
    schemas: [
      {
        label: t('到货车次'),
        field: 'hid.djNo',
        component: 'Input',
      },
      {
        label: t('车牌号'),
        field: 'hid.carNo',
        component: 'Input',
      },
      {
        label: t('计划到货日期'),
        field: 'hid.planDate',
        component: 'RangePicker',
        // component: 'DatePicker',
        componentProps: {
          // format: 'YYYY-MM-DD HH:mm',
          // valueFormat: 'YYYY-MM-DD HH:mm',
          // showTime: { format: 'HH:mm' },
        },
      },
      {
        label: t('供应商'),
        field: 'hid.venName',
        component: 'Input',
      },
      {
        label: t('采购订单号'),
        field: 'poCode',
        component: 'Input',
      },
      {
        label: t('合同号'),
        field: 'contractCode',
        component: 'Input',
      },
      {
        label: t('存货'),
        field: 'hid.invName',
        component: 'Input',
      },
      // {
      //   label: t('司机'),
      //   field: 'hid.cdriver',
      //   component: 'Input',
      // },
      // {
      //   label: t('司机电话'),
      //   field: 'hid.driverPhone',
      //   component: 'Input',
      // },
      // {
      //   label: t('运输单位'),
      //   field: 'hid.carVenName',
      //   component: 'Input',
      // },
      // {
      //   label: t('U8单号'),
      //   field: 'u8Code',
      //   component: 'Input',
      // },
      {
        label: t('制单人'),
        field: 'hid.createByName',
        component: 'Input',
      },
    ],
    fieldMapToTime: [['hid.planDate', ['planDate_gte', 'planDate_lte']]],
  };

  //配置表格表头菜单
  const tableColumns: BasicColumn[] = [
    {
      title: t('到货车次'),
      dataIndex: 'hid.djNo',
      key: 'hid.dj_no',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('车牌号'),
      dataIndex: 'hid.carNo',
      key: 'hid.car_no',
      sorter: true,
      width: 80,
      align: 'center',
    },
    {
      title: t('类型'),
      dataIndex: 'hid.carType',
      key: 'hid.car_type',
      sorter: true,
      width: 80,
      dictType: 'mf_carplan_type',
    },
    {
      title: t('净重'),
      dataIndex: 'hid.jzWeight',
      key: 'hid.jz_weight',
      sorter: true,
      width: 80,
      customRender: ({ record }) => {
        // console.log(record,'record====');
        // 保留4位小数
        return record.hid?.jzWeight ? Number(record.hid?.jzWeight).toFixed(4) : '0.0000';
      },
    },
    {
      title: t('确认到货重量'),
      dataIndex: 'qrWeight',
      key: 'a.qr_weight',
      sorter: true,
      width: 150,
      customRender: ({ record }) => {
        // 保留两位小数
        return record.qrWeight ? Number(record.qrWeight).toFixed(4) : '';
      },
    },
    {
      title: t('件数'),
      dataIndex: 'iqty',
      key: 'a.iqty',
      sorter: true,
      width: 80,
    },
    {
      title: t('合同号'),
      dataIndex: 'contractCode',
      key: 'a.contract_code',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('供应商'),
      dataIndex: 'venName',
      key: 'a.ven_name',
      sorter: true,
      width: 200,
      align: 'left',
    },
    {
      title: t('入库仓库'),
      dataIndex: 'rkStore',
      key: 'a.rk_store',
      sorter: true,
      width: 120,
      dictType: 'mf_rk_store',
    },
    {
      title: t('存货编码'),
      dataIndex: 'invCode',
      key: 'a.inv_code',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'invName',
      key: 'a.inv_name',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'invStd',
      key: 'a.inv_std',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('采购订单号'),
      dataIndex: 'poCode',
      key: 'a.po_code',
      sorter: true,
      width: 150,
    },
    {
      title: t('折算系数'),
      dataIndex: 'irate',
      key: 'a.irate',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('状态'),
      dataIndex: 'cstatus',
      key: 'a.cstatus',
      sorter: true,
      width: 80,
      dictType: 'mf_plan_detail_status',
    },
    {
      title: t('计重方式'),
      dataIndex: 'weightType',
      key: 'a.weightType',
      sorter: true,
      width: 80,
    },
    {
      title: t('计划到货日期'),
      dataIndex: 'hid.planDate',
      key: 'hid.plan_date',
      sorter: true,
      width: 150,
      align: 'center',
    },
    {
      title: t('计划到货重量'),
      dataIndex: 'planWeight',
      key: 'a.plan_weight',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('海关重量'),
      dataIndex: 'hgWeight',
      key: 'a.hg_weight',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('制单人'),
      dataIndex: 'hid.createByName',
      key: 'hid.create_by_name',
      sorter: true,
      width: 120,
      align: 'left',
    },
  ];

  const tableColumns3: BasicColumn[] = [
    {
      title: t('采购订单号'),
      dataIndex: 'poCode',
      width: 150,
    },
    {
      title: t('存货编码'),
      dataIndex: 'invCode',
      width: 150,
    },
    {
      title: t('存货名称'),
      dataIndex: 'invName',
      width: 150,
    },
    {
      title: t('规格型号'),
      dataIndex: 'invStd',
      width: 150,
    },
    {
      title: t('供应商编码'),
      dataIndex: 'venCode',
      width: 150,
    },
    {
      title: t('供应商名称'),
      dataIndex: 'venName',
      width: 150,
    },
   
    {
      title: t('合同号'),
      dataIndex: 'contractCode',
      width: 150,
    },
    {
      title: t('剩余重量'),
      dataIndex: 'qty',
      width: 150,
    },
    {
      title: t('计划重量'),
      dataIndex: 'planWeight',
      width: 200,
      editRow: true,
      editComponent: 'InputNumber',
      // editComponentProps:{
      //   onChange:(e)=>{
      //     console.log(e);
      //     e = 20
      //   }
      // },
      editRule: true,
    },
  ];

  //配置表格右边操作按钮
  const actionColumn: BasicColumn = {
    width: 120,
    align: 'left',
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑'),
        onClick: handleForm.bind(this, { id: record.id }),
        auth: 'mf:dh:mfCarplanDhH:edit',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除数据'),
        popConfirm: {
          title: t('是否确认删除数据'),
          confirm: handleDelete.bind(this, { id: record.id }),
        },
        auth: 'mf:dh:mfCarplanDhH:edit',
        ifShow: () => record.cstatus != '3' && record.cstatus != '4',
      },
    ],
  };

  const inputFormSchemas: FormSchema[] = [
    {
      label: t(''),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        rows:5
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    // schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const selectedRowKeysRef = ref<string[]>([]);
  const [registerDrawer, { openDrawer }] = useDrawer();

  const [registerTable, { reload, setProps, getSelectRows }] = useTable({
    api: listPushData,
    beforeFetch: (params) => {
      params['hid.planType']= '1';
      return params;
    },
    afterFetch: (params) => {
      console.log(params,'params=====');
      return params;
    },
    columns: tableColumns, //配置表格内容数组对象
    formConfig: searchForm, //配置表单内容
    showTableSetting: true, //表格右上角3个默认按钮
    useSearchForm: true, //表单是否展示
    canResize: true, //表格是否flex布局
    // scroll: {
    //   y: 250,
    // },
    rowSelection: {
      type: 'checkbox',
    },
    resizeHeightOffset: 80,
    defaultRowSelection: {
      onChange: (selectedRowKeys: string[], _selectedRows: Recordable[]) => {
        selectedRowKeysRef.value = selectedRowKeys;
      },
    },
    showSummary: true,
    summaryFunc: handleSummary,
  });

  function handleSummary(tableData: Recordable[]) {
    const totaljzWeight = tableData.reduce((prev, next) => {
      prev += next.hid.jzWeight ? next.hid.jzWeight : 0;
      return prev;
    }, 0);
    const totalqrWeight = tableData.reduce((prev, next) => {
      prev += next.qrWeight ? next.qrWeight : 0;
      return prev;
    }, 0);
    /** planWeight */
    const totalPlanWeight = tableData.reduce((prev, next) => {
      prev += next.planWeight ? next.planWeight : 0;
      return prev;
    }, 0);
     /** hgWeight */
     const totalHgWeight = tableData.reduce((prev, next) => {
      prev += next.hgWeight ? next.hgWeight : 0;
      return prev;
    }, 0);
    return [
      {
        _row: '合计',
        hid: { jzWeight: totaljzWeight.toFixed(2) },
        qrWeight: totalqrWeight.toFixed(2),
        planWeight: totalPlanWeight.toFixed(2),
        hgWeight: totalHgWeight.toFixed(2),
      },
    ];
  }

  onMounted(() => {
    if (!props.data.picno) {
      setProps({
        actionColumn: actionColumn,
      });
    }
  });


  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }
  
  async function btnSdPush() {
    if (getSelectRows().length) {

      var selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await pushdata({ ids: selIds.value, planType: 1 });
      selectedRowKeysRef.value = [];
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请先选择车次！！');
    }
  }

  // 鼠标行点击事件，获取上表数据
  function handleTestDataChildRowClick(record: Recordable) {
    // totalWeight.value = record.planWeight;
    // 把选中的数据里面的确认发货重量全部累加给totalWeight
    for (const record of xqtable3.getDataSource()) {
      totalWeight.value += Number(record.planWeight);
    }
  }

  async function handleOverSubmit(record: Recordable) {
    try {
      const data = await validate();
      data.id = overData.value.id
      data.djNo = overData.value.djNo
      data.cstatus = '2'
      setModalProps({ confirmLoading: true });
      const res = await updateCzStatusByHand(data);
      selectedRowKeysRef.value = [];
      showMessage(res.message);
      handleSuccess();
      closeModal();
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  async function handleDelete(record: Recordable) {
    const res = await CarplanDhDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  function handleSuccess() {
    emit('success');
    reload();
  }

  function handleSelectionChange({ keys , rows}) {
    selectedRowKeysRef.value = keys;
    // 统计累加rows 数组的每一项的qrWeight ，totalWeight.value 小数点后保留4位
    totalWeight.value = rows.reduce((pre, cur) => pre + Number(cur.qrWeight || 0), 0).toFixed(4);
    // for (const record of rows) { 
    //   totalWeight.value += Number(record.qrWeight);
    //   console.log(totalWeight.value,'totalWeight.value====',record.qrWeight)
    // }
  }
</script>